﻿using System;
using System.Collections.Generic;
using wojilu.Apps.Qycms.Domain;
using wojilu.Common;
using wojilu.IO;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Members.Users.Interface;
using wojilu.Members.Users.Service;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class UserController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }
        public virtual IUserService userService { get; set; }

        public UserController()
        {
            logService = new SiteLogService();
            userService = new UserService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void AdminList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            var condition = String.Empty;
            DataPage<User> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            Int32 isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " and isclass = 1 ";
                    break;

                case 2:
                    condition += " and isclass = 0 ";
                    break;
            }
            Int32 inputclassid = ctx.GetInt("inputclassid");
            switch (inputclassid)
            {
                case 1:
                    condition += " and inputclassid = 1 ";
                    break;

                case 2:
                    condition += " and inputclassid = 0 ";
                    break;
            }
            var powergroup = ctx.GetInt("powergroup");
            if (powergroup != 0)
            {
                condition += " and GroupId = " + powergroup;
            }
            if (!condition.StrIsNullOrEmpty() && 
            condition.StartsWith(" and "))
            {
                condition = StringHelper.Right(condition, condition.Length - 5);
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "asc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = User.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void AdminAdd()
        {
            SetPublic();
            setpublic();
            target(AdminAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("usercheck", to(UserCheck));
            set("tab", "true");
            List<PowerGroup> p = PowerGroup.find(" order by id asc").list();
            bind("list", p);
        }

        private User validateUser()
        {
            String name = ctx.Post("username");
            String pwd = ctx.Post("password2");
            String pageUrl = name;
            String email = strUtil.SubString(ctx.Post("email"), RegPattern.EmailLength);

            if (strUtil.IsNullOrEmpty(name))
            {
                errors.Add(lang("exUserName"));
            }
            else if (name.Length < config.Instance.Site.UserNameLengthMin)
            {
                errors.Add(string.Format(lang("exUserNameLength"), config.Instance.Site.UserNameLengthMin));
            }
            else
            {
                name = strUtil.SubString(name, config.Instance.Site.UserNameLengthMax);
            }
            if (strUtil.IsAbcNumberAndChineseLetter(name) == false) errors.Add(lang("exUserNameError"));


            if (strUtil.IsNullOrEmpty(pwd))
                errors.Add(lang("exPwd"));
            else
                pwd = strUtil.CutString(pwd, 20);

            if (strUtil.IsNullOrEmpty(email))
                errors.Add(lang("exEmail"));
            else
            {
                if (RegPattern.IsMatch(email, RegPattern.Email) == false) errors.Add(lang("exUserMail"));
            }

            User user = new User();
            user.Name = name;
            user.Pwd = pwd;
            user.Url = pageUrl;
            user.RealName = ctx.Post("name");
            user.Email = ctx.Post("email");
            user.Gender = ctx.PostInt("sex");
            user.GroupId = ctx.PostInt("powergroup");
            user.inputclassid = ctx.PostInt("inputclassid");
            user.isclass = 1;
            user.mcid = 0;
            user.isremote = ctx.PostInt("isremote");
            user.LastLoginIp = ctx.web.ClientIp;
            return user;
        }

        [HttpPost]
        public virtual void AdminAddDo()
        {
            // 验证
            User user = validateUser();
            if (errors.HasErrors)
            {
                run(AdminAdd);
                return;
            }

            // 管理员注册
            user = userService.Register(user, ctx);

            if ((user == null) || errors.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("mangerlist_add_log") + lang("log_extra_no"), "{Erros:'" + errors.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false" + errors.ErrorsText);
            }
            else
            {
                user.RoleId = 5;
                user.update();
                logService.Add((User)ctx.viewer.obj, lang("mangerlist_add_log") + lang("log_extra_ok"), "{Id:" + user.Id + ", Name:'" + user.Name + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
        }

        [HttpGet]
        public virtual void AdminEdit(Int64 id)
        {
            SetPublic();
            setpublic();
            target(AdminEditDo, id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("usercheck", to(UserCheck));
            set("tab", "true");
            List<PowerGroup> p = PowerGroup.find(" order by id asc").list();
            bind("list", p);
            User u = User.findById(id);
            bind("memberinfo", u);
        }

        [HttpPost]
        public virtual void AdminEditDo(Int64 id)
        {
            User u = User.findById(id);
            var password = ctx.Post("password2");
            u.Pwd = userService.HashPwd(password, u.PwdSalt);
            u.RealName = ctx.Post("name");
            u.GroupId = ctx.PostInt("powergroup");
            u.inputclassid = ctx.PostInt("inputclassid");
            u.isremote = ctx.PostInt("isremote");
            u.Email = ctx.Post("email");
            u.Gender = ctx.PostInt("sex");
            Result result = u.update();
            logService.Add((User)ctx.viewer.obj, lang("mangerlist_edit_log") + lang("log_extra_ok"), "{Id:" + u.Id + ", Name:'" + u.Name + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
        }

        [HttpPost]
        public virtual void AdminDel()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<User>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("mangerlist_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("mangerlist_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void AdminSetting()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<User>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("adverttypemain_setting_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("adverttypemain_setting_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void UserCheck()
        {
            var UserName = ctx.Post("username");
            ctx.web.ResponseWrite(User.count(" name = '" + UserName + "'") > 0 ? "false" : "true");
            ctx.web.ResponseEnd();
        }

    }
}
